﻿using System;
using System.Globalization;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;

/// <summary>
/// Administration page to upload new and manage available songs.
/// </summary>
public partial class Admin_Default : Page
{
	/// <summary>
	/// Event handler that is called after a new song is saved to the database.
	/// Saves the uploaded song file to the Songs folder.
	/// </summary>
	/// <param name="sender">Sender.</param>
	/// <param name="e">Event arguments.</param>
	protected void sdsSongs_Inserted( object sender, SqlDataSourceStatusEventArgs e )
	{
		// Get the file upload control.
		FileUpload fupSongFile = (FileUpload) this.dvUpload.FindControl( "fupSongFile" );

		if( fupSongFile != null && fupSongFile.HasFile )
		{
			// Get the ID of the new song.
			object id = e.Command.Parameters[ "@NewId" ].Value;

			// Get the application relative path of the song file.
			string virtualPath = String.Format( CultureInfo.InvariantCulture, "~/Songs/{0}.zip", id );

			// Build the physical path and save the uploaded file to that path.
			fupSongFile.SaveAs( this.Server.MapPath( virtualPath ) );
		}
	}



	/// <summary>
	/// Event handler that is called before the song record is removed from the database.
	/// Deletes the song file from the Songs folder.
	/// </summary>
	/// <param name="sender">Sender.</param>
	/// <param name="e">Event arguments.</param>
	protected void sdsSongs_Deleting( object sender, SqlDataSourceCommandEventArgs e )
	{
		// Get the ID of the song to be deleted.
		object id = e.Command.Parameters[ "@original_ID" ].Value;

		// Get the application relative path of the song file.
		string virtualPath = String.Format( CultureInfo.InvariantCulture, "~/Songs/{0}.zip", id );

		// Build the physical path and remove the file from the disk.
		File.Delete( this.Server.MapPath( virtualPath ) );	
	}
}
